import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, Modal, ScrollView, StyleSheet } from 'react-native';
import { px2dp, scale } from '~/utils/px2dp';
import Icon from 'react-native-vector-icons/Ionicons';
import { useTranslation } from 'react-i18next';
import { getWuXueDBCourseApi, saveUserSelectTitleId, checkCourseByDevices } from '~/api/acupoints';
import { useNavigation } from '@react-navigation/native';
import { checkAndRequestLocationPermissions, checkAndRequestBluetoothPermissions } from '~/utils/permission';
import { deviceStore, RecordKeys, Storage, observer, webSocketStore } from '~/store';
import BleConnection from '~/utils/ble/connect';

const Bleconnect = BleConnection.getInstance();
type ActionType = 'addDevice' | 'switchCourse';

interface Props {
    visible: boolean;
    device_sn: string;
    titleId?: string;
    actionType?: ActionType;
    onToggleVisible: Function;
    switchCallBack?: Function;
    changeTitleId?: Function;
}
export default observer((props: Props) => {
    const {
        visible,
        onToggleVisible,
        device_sn,
        titleId = '',
        actionType = 'addDevice',
        switchCallBack,
        changeTitleId,
    } = props;
    const { t } = useTranslation();
    const navigation: any = useNavigation();
    const { deviceList } = webSocketStore;
    const [listData, setListData] = useState([]);
    const [selectInfo, setSelectInfo] = useState({
        add_time: null,
        base_course_icon: '',
        base_course_img: '',
        id: '',
        name: '',
        num: '',
        title_img: '',
    });
    const getData = () => {
        getWuXueDBCourseApi().then((res) => {
            setListData(res.baseCourse);
        });
    };
    useEffect(() => {
        if (titleId) {
            setSelectInfo({ ...selectInfo, id: titleId });
        }
    }, [titleId]);

    // 开始绑定yy01以及相关设备
    const changeItem = async (row) => {
        if (row.id == titleId) {
            Toast.show({ content: t('Acupoints.t74') });
            return;
        }
        // 假如是切换
        if (actionType == 'switchCourse') {
            const armariumDeviceChang = deviceList.map((item) => item.armarium_device_chang);
            const resultString = `'${armariumDeviceChang.join("','")}'`;
            const res = await checkCourseByDevices({ title_id: row.id, device_sn_str: resultString });
            // 检测有无小包可写入
            if (res.status !== 1) {
                Toast.show({ content: res.msg, layout: 'top' });
                onToggleVisible();
                return;
            }
        }
        await saveUserSelectTitleId({ title_id: row.id });
        if (actionType == 'addDevice') {
            await Storage.setItem(RecordKeys.titleId, row.id);
            if (device_sn) {
                onToggleVisible();
                changeTitleId && changeTitleId(row.id);
                navigation.navigate('AddDeviceScreen', { device_sn, titleId: row.id });
            } else {
                const hasLocationPermissions = await checkAndRequestLocationPermissions();
                const hasBluetoothPermissions = await checkAndRequestBluetoothPermissions();
                if (hasLocationPermissions && hasBluetoothPermissions) {
                    if (deviceStore.device.deviceStatus == 0) {
                        Toast.show({ content: t('Acupoints.t18'), layout: 'top' });
                        return;
                    }
                    Bleconnect.scan(5);
                    setSelectInfo(row);
                    onToggleVisible();
                    navigation.navigate('AddDeviceScreen', { device_sn, titleId: row.id });
                } else {
                    onToggleVisible && onToggleVisible();
                    Toast.show({ content: t('Acupoints.t19'), layout: 'top' });
                }
            }
        } else {
            // 切换疗程
            if (!device_sn) {
                onToggleVisible();
                return;
            }
            switchCallBack && switchCallBack(row.id);
        }
    };
    useEffect(() => {
        getData();
    }, []);

    return (
        <Modal transparent={true} visible={visible} statusBarTranslucent={true} hardwareAccelerated={true}>
            <View style={styles.modalOverlay}>
                <View style={[styles.modalContent]}>
                    <View style={[styles.row, styles.between]}>
                        <View />
                        <Text style={styles.title}>{t('Acupoints.t25')}</Text>
                        {/* <View /> */}
                        <TouchableOpacity onPress={() => onToggleVisible && onToggleVisible()}>
                            <Icon name={'close-sharp'} size={px2dp(40)} color={'#666666'}></Icon>
                        </TouchableOpacity>
                    </View>
                    <Text style={styles.tips}>{t('Acupoints.t26')}</Text>
                    <ScrollView
                        contentContainerStyle={styles.contentContainerStyle}
                        showsVerticalScrollIndicator={false}>
                        <View>
                            {listData.map((item: any, index) => {
                                return (
                                    <TouchableOpacity
                                        onPress={() => changeItem(item)}
                                        key={item.id}
                                        style={[styles.listItem, styles.row, styles.between]}>
                                        <Text>{item?.name}</Text>
                                        <Icon
                                            name={'ellipse-sharp'}
                                            size={px2dp(40)}
                                            color={
                                                selectInfo.id == item.id ? '#1877FF' : 'rgba(23, 119, 255, 0.12)'
                                            }></Icon>
                                    </TouchableOpacity>
                                );
                            })}
                        </View>
                    </ScrollView>
                </View>
            </View>
        </Modal>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'flex-end',
    },
    modalContent: {
        backgroundColor: '#fff',
        padding: px2dp(24),
        borderRadius: px2dp(48),
        maxHeight: '60%',
        minHeight: '60%',
    },
    title: {
        color: '#000',
        fontSize: scale(28),
        fontWeight: '500',
    },
    tips: {
        color: '#666',
        fontSize: scale(26),
        marginVertical: px2dp(24),
    },
    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
    },
    listItem: {
        backgroundColor: '#F4F4F4',
        marginTop: px2dp(24),
        borderRadius: px2dp(12),
        padding: px2dp(24),
    },
});
